package com.lmx.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.studyrecords.StudyrecordsAddRequest;
import com.lmx.project.model.dto.studyrecords.StudyrecordsQueryRequest;
import com.lmx.project.model.dto.studyrecords.StudyrecordsUpdateRequest;
import com.lmx.project.model.dto.users.UserCountQueryRequest;
import com.lmx.project.model.dto.users.UsersCountVo;
import com.lmx.project.model.entity.Studyrecords;
import com.lmx.project.model.entity.Users;
import com.lmx.project.model.vo.StudyrecordsVo;
import com.lmx.project.model.vo.UsersVo;
import com.lmx.project.service.StudyrecordsService;
import com.lmx.project.service.UsersService;
import com.lmx.project.untils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author lmx
 * 本类负责有关提交学习记录的增删改查
 */
@RestController
@RequestMapping("/studyrecord")
@Slf4j
public class StudyRecordsController {
    @Resource
    private StudyrecordsService studyrecordsService;
//    @Resource
//    private FileUntil fileUntil;

    @Resource
    private FileUtil fileUtil;
    @Resource
    private UsersService usersService;

    private String studydir = "studydir/";




    /**
     * 增加学习记录
     */
    @PostMapping()
    public BaseResponse<Long> addRecord( StudyrecordsAddRequest studyrecordsAddRequest, HttpServletRequest request) throws IOException {
        log.info(studyrecordsAddRequest.toString());
        if (studyrecordsAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//
//        if (studyrecordsAddRequest.getAddStudyFile() == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请提交学习文件");
//        }

        if (studyrecordsAddRequest.getLearningcontent() == null || studyrecordsAddRequest.getLearningcontent().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写学习内容");
        }

        if (studyrecordsAddRequest.getAddStudyFile() == null ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请上传文件");
        }


        Studyrecords studyrecords = new Studyrecords();
        BeanUtils.copyProperties(studyrecordsAddRequest, studyrecords);

//        保存文件
        if (studyrecordsAddRequest.getAddStudyFile() != null) {
            MultipartFile addAvatarFile = studyrecordsAddRequest.getAddStudyFile();




            String b = fileUtil.saveMultipartFile(addAvatarFile, studydir );
            if (b != null) {
                studyrecords.setFileurl(b);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件上传错误，请重试");
            }
        }


//        获取当前登录用户
//        BaseResponse<Users> usersByid = usersController.getUsersByid(request);
       UsersVo usersVo= usersService.getUserCurrent(request);
        if (usersVo == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请先登录");
        }
        Long id = usersVo.getId();
//
        studyrecords.setUserid(id);
        boolean save = studyrecordsService.save(studyrecords);
        if (save) {
            return ResultUtils.success(studyrecords.getId());
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请联系管理员");
        }

    }


    @PostMapping("uploadimage")
    public BaseResponse<String> uploadFile(MultipartFile file) throws IOException {

        if (file == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
//        String originalFilename = file.getOriginalFilename();
////            后缀名
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
//
//        String resultfilename = UUID.randomUUID().toString().replace("-", "");


        String b = fileUtil.saveMultipartFile(file, studydir);

        String preUrl = fileUtil.getPreUrl();

        if (b != null) {
            return ResultUtils.success(preUrl + b);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

    }

    /**
     * 删除学习记录
     * TODO 管理员
     */
    @DeleteMapping()
    public BaseResponse<Boolean> DeleteRecrd(Long id) {
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Studyrecords byId = studyrecordsService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该记录不存在");
        }
//        删除云存储中的图片
        String fileurl = byId.getFileurl();
//        String[] split = fileurl.split("/");
//        String key = split[split.length - 2] + "/" + split[split.length - 1];
        fileUtil.removeFile(fileurl);

//        删除数据库中的记录
        boolean b = studyrecordsService.removeById(id);
        if (b) {
            return ResultUtils.success(true);
        } else {
            log.info("数据库记录删除失败");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除失败，请联系管理员或稍后重试");
        }

    }


    /**
     * 修改学习记录
     * TODO 管理员
     */

    @PutMapping
    public BaseResponse<Long> UpdateRecord(StudyrecordsUpdateRequest studyrecordsUpdateRequest) throws IOException {
        if (studyrecordsUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        if (studyrecordsUpdateRequest.getId() == null || studyrecordsUpdateRequest.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Studyrecords studyrecords = new Studyrecords();
        BeanUtils.copyProperties(studyrecordsUpdateRequest, studyrecords);

//        保存文件
        if (studyrecordsUpdateRequest.getAddStudyFile() != null) {
            MultipartFile addAvatarFile = studyrecordsUpdateRequest.getAddStudyFile();


            String originalFilename = addAvatarFile.getOriginalFilename();
//            后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());

            String resultfilename = UUID.randomUUID().toString().replace("-", "");


            String b = fileUtil.saveMultipartFile(addAvatarFile, studydir);
            if (b != null) {
                studyrecords.setFileurl(b);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件上传错误，请重试");
            }
        }

        boolean save = studyrecordsService.updateById(studyrecords);
        if (save) {
            return ResultUtils.success(studyrecords.getId());
        } else {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请联系管理员");
        }

    }


    /**
     * 查询当前用户的提交记录
     */

    @GetMapping()
    public BaseResponse<List<Studyrecords>> getRecordsByUserid(HttpServletRequest request) throws IOException {


        UsersVo usersByid = usersService.getUserCurrent(request);
        if (usersByid == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请先登录");
        }


        Long userid = usersByid.getId();

        LambdaQueryWrapper<Studyrecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Studyrecords::getUserid, userid);
        List<Studyrecords> list = studyrecordsService.list(queryWrapper);

        String preUrl = fileUtil.getPreUrl();
        list.stream().forEach(studyrecords -> {
            studyrecords.setFileurl(preUrl + studyrecords.getFileurl());
        });

        return ResultUtils.success(list);
    }

    /**
     * 管理员查看提交记录
     * TODO 管理员
     */
    @GetMapping("manger")
    public BaseResponse<Page<StudyrecordsVo>> getRecordsByAdmin(StudyrecordsQueryRequest studyrecordsQueryRequest) {

        if (studyrecordsQueryRequest == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        LambdaQueryWrapper<Studyrecords> queryWrapper = new LambdaQueryWrapper<>();

        if (studyrecordsQueryRequest.getUserid() != null) {
            queryWrapper.eq(Studyrecords::getUserid, studyrecordsQueryRequest.getUserid());
        }
//     开始时间小于创建时间
        if (studyrecordsQueryRequest.getStarttime() != null) {
            queryWrapper.le(Studyrecords::getCreatedtime, studyrecordsQueryRequest.getStarttime());
        }
// 结束时间大于创建时间
        if (studyrecordsQueryRequest.getEndtime() != null) {
            queryWrapper.ge(Studyrecords::getCreatedtime, studyrecordsQueryRequest.getEndtime());
        }

//        Page<Studyrecords> page = studyrecordsService.page(new Page<>(studyrecordsQueryRequest.getCurrent(), studyrecordsQueryRequest.getPageSize()), queryWrapper);
        Page<StudyrecordsVo> page=studyrecordsService.getstudurecordsByCondition(studyrecordsQueryRequest);
        String preUrl = fileUtil.getPreUrl();
        page.getRecords().stream().forEach(studyrecords -> {
            studyrecords.setFileurl(preUrl + studyrecords.getFileurl());
        });

        return ResultUtils.success(page);
    }




    /**
     * 获取用户的提交次数排行
     * TODO 管理员
     */
    @PostMapping("count")
    public BaseResponse<List<UsersCountVo>> getUserCountVo(@RequestBody UserCountQueryRequest userCountQueryRequest) {

        if (userCountQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userCountQueryRequest.getCurrent() == 0 || userCountQueryRequest.getPageSize() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写查询页数");
        }

        userCountQueryRequest.setCurrent((userCountQueryRequest.getCurrent() - 1)
                * userCountQueryRequest.getPageSize());
//        String res="(";
//        List<String> gardlist = userCountQueryRequest.getGardlist();
//        if (gardlist !=null && gardlist.size()>0){
//
//            for (int i = 0; i< gardlist.size(); i++){
//                res=res+"'"+gardlist.get(i)+"'";
//                if (i!=gardlist.size()-1) {
//                    res += ",";
//                }
//            }
//            res+=")";
//
//        }
//        userCountQueryRequest.setGardstring(res);
        List<UsersCountVo> usersCountVo = usersService.getUsersCountVo(userCountQueryRequest);
        return ResultUtils.success(usersCountVo);
    }
}
